<template>
  <el-dialog class="mapCalibration"
             title="地图标定"
             :visible.sync="dialogVisible"
             width="48%"
             :append-to-body='true'
             :before-close="closeDialog">
    <el-form :model="form"
             label-width="100px"
             size="medium"
             :rules="rules"
             ref="calForm">
      <el-form-item label="对象选择:"
                    :required="true"
                    prop="displayname">
        <el-input v-model="form.displayname"
                  :readonly="true"
                  autocomplete="off"
                  style="width:60%"
                  placeholder="请选择对象"
                  @click.native="showTree"></el-input>
        <div v-show="isShow"
             class="treeDemo">
          <el-tree ref="tree"
                   :default-expand-all="true"
                   :props="defaultProps"
                   :data="treeData"
                   @check-change="checkChnage"
                   :render-content="renderContent"
                   :expand-on-click-node="false">
          </el-tree>
          <!-- <div class="opreation">
            <el-button type="primary"
                       @click="handleChooseObject">确定</el-button>
            <el-button type="danger"
                       @click="handleDisChoose">取消</el-button>
          </div> -->
        </div>
      </el-form-item>
      <el-form-item label="地理属性:"
                    :required="true"
                    prop="currentGisPropertye">
        <el-select v-model="form.currentGisPropertye"
                   placeholder="请选择地理属性"
                   value-key="displayname"
                   @change="handleChooseGisProperty">
          <el-option v-for="(item,index) in gisProperyList"
                     :key="index"
                     :label="item.displayname"
                     :value="item"></el-option>

        </el-select>
      </el-form-item>
      <el-form-item label="位置描述:"
                    :required="true"
                    prop="currentGisPropertye_location">
        <el-input v-model="form.currentGisPropertye_longitude"
                  style="width:25%"
                  placeholder="经度"
                  :readonly="true">
        </el-input>
        <el-input v-model="form.currentGisPropertye_latitude"
                  style="width:25%"
                  placeholder="纬度"
                  :readonly="true">
        </el-input>
        <el-input v-model="form.currentGisPropertye_location"
                  style="width:40%"
                  placeholder="位置描述">

        </el-input>
      </el-form-item>
      <template v-for="(item,index) in repPropertyList">
        <el-form-item :required="true"
                      :key="index"
                      :label="item.displayname">
          <template v-if="item.propertyType==='GisData'">
            <el-input v-model="item.longitude"
                      placeholder="经度"
                      style="width:30%"></el-input>
            <el-input v-model="item.latitude"
                      placeholder="纬度"
                      style="width:30%"></el-input>
            <el-input v-model="item.address"
                      placeholder="位置描述"
                      style="width:30%"></el-input>
          </template>
          <template v-else-if="item.propertyType==='TimeInterval'">
            <el-date-picker type="datetime"
                            v-model="item.timeStart"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            style="width:40%"
                            placeholder="请输入开始日期">
            </el-date-picker>
            <el-date-picker type="datetime"
                            v-model="item.timeEnd"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            style="width:40%"
                            placeholder="请输入结束日期">
            </el-date-picker>
          </template>
          <template v-else-if="item.propertyType==='DateTime'">
            <el-date-picker type="datetime"
                            v-model="item.value"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            style="width:40%"
                            placeholder="请输入时间">
            </el-date-picker>
          </template>
          <template v-else>
            <el-input v-model="item.value"
                      :placeholder="'请输入'+item.displayname"
                      style="width:50%"></el-input>
          </template>
        </el-form-item>
      </template>

      <!-- <el-form-item label="属性:">
        <template v-for="(prop,index) in props_arr">
          <div :key="index"
               style="margin-bottom:10px;">
            <el-select style="width:30%"
                       v-model="prop.property"
                       placeholder="请选择属性"
                       value-key="displayname"
                       @change="checkReadyOnly(prop['property'],index)">
              <el-option v-for="(item,index) in otherProperyList"
                         :key="index"
                         :label="item.displayname"
                         :value="item"></el-option>
            </el-select>
            <template v-if="prop.property.propertyType==='GisData'">
              <el-input v-model="prop.property.longitude"
                        placeholder="经度"
                        style="width:20%"></el-input>
              <el-input v-model="prop.property.latitude"
                        placeholder="纬度"
                        style="width:20%"></el-input>
              <el-input v-model="prop.property.address"
                        placeholder="位置描述"
                        style="width:25%"></el-input>
            </template>
            <template v-else-if="prop.property.propertyType==='TimeInterval'">
              <el-date-picker type="datetime"
                              v-model="prop.property.timeStart"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              style="width:30%"
                              placeholder="请输入开始日期">
              </el-date-picker>
              <el-date-picker type="datetime"
                              v-model="prop.property.timeEnd"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              style="width:30%"
                              placeholder="请输入结束日期">
              </el-date-picker>
            </template>
            <template v-else-if="prop.property.propertyType==='DateTime'">
              <el-date-picker type="datetime"
                              v-model="prop.property.value"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              style="width:40%"
                              placeholder="请输入时间">
              </el-date-picker>
            </template>
            <template v-else>
              <el-input v-if="prop.property"
                        v-model="prop.property.value"
                        :placeholder="'请输入'+prop.property.displayname"
                        style="width:50%"></el-input>
            </template>
            <template v-if="index>0">
              <i class="el-icon-remove"
                 title="删除"
                 @click="removeOtherProperty(index)"></i>
            </template>
          </div>
        </template>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   @click="addOtherProperty"></el-button>

      </el-form-item> -->
    </el-form>
    <div slot="footer"
         class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary"
                 @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import util from '@/utils'
import { getGisTree, findOperateProperties, saveInstance } from '@/api/map'
import { gettree } from '@/api/relationFraph'
export default {
    data () {
        return {
            unifiedUserUrl: '',
            current_selectd_node: '',
            // gis属性下拉框
            gisProperyList: [],
            // 代表属性下拉框
            repPropertyList: [],
            // 非代表属性下拉框
            otherProperyList: [],
            // 非代表属性缓存下拉框
            chacheOtherProperyList: [],
            isShow: false,
            treeData: [],
            props_arr: [{ property: '' }],
            defaultProps: {
                children: 'children',
                label: 'displayname'
            },
            // 规则
            rules: {
                displayname: [{ required: true, message: '请选择对象', trigger: 'blur' }],
                currentGisPropertye: [{ required: true, message: '请选择地理属性', trigger: 'blur' }],
                currentGisPropertye_location: [{ required: true, message: '请输入位置描述', trigger: 'blur' }]

            },
            // 地图标定对话框的表单对象
            form: {
                objectUri: '',
                displayname: '',
                // 当前gis属性
                currentGisPropertye: '',
                // 当前gis属性地理位置描述
                currentGisPropertye_location: '',
                currentGisPropertye_longitude: '',
                currentGisPropertye_latitude: '',
                region1: ''
            }
        }
    },
    props: {
        dialogVisible: Boolean,
        position: Object,
        map:Object
    },
    created () {
        this.unifiedUserUrl = this.$store.state.unifiedUserUrl
        this.form.currentGisPropertye_longitude = this.position.lng
        this.form.currentGisPropertye_latitude = this.position.lat
    },
    methods: {
        // 选择对象
        checkChnage (node, isChecked, data) {
            // this.objectList = []
            // let checkedNodes = this.$refs.tree.getCheckedNodes()
            // checkedNodes.forEach(element => {
            //     if (element.parenturi) {
            //         this.objectList.push(element.uri)
            //     }
            // })
        },
    // 关闭对话框
        closeDialog () {
            this.$emit('closeDialog')
        },
        // 显示对象树
        showTree () {
            this.loadTree()
            this.isShow = true
        },
        // 查找出一级目录
        handleLevelOne(data, parent) {
            var tree = []
            var temp
            for (var i = 0; i < data.length; i++) {
            if (data[i].parentkey == parent) {
                var obj = data[i]
                obj.label = data[i].displayname
                obj.value = data[i].uri
                obj.parenturi = data[i].parenturi
                obj.parent = parent
                temp = this.handleLevelOne(data, data[i].ownkey)
                if (temp.length > 0) {
                obj.children = temp
                }
                tree.push(obj)
            }
            }
            return tree
        },
        // 加载左侧菜单树
        loadTree (type) {
            let obj = {
                uriList: '',
                typeList: ['socialaccount', 'socialdynamic', 'keyfigures', 'focusgroup'].join(',')
            }
            gettree(obj).then(res => {
                this.treeData =this.handleLevelOne(res.data)
            })
            // getGisTree().then(response => {
            //     let tree = response.data
            //     // 树状菜单去除备注节点
            //     tree = tree.filter(item => {
            //         return item.uri != 'com.scistor.object.note'
            //     })
            //     this.treeData = util.parseUriData(tree)
            // })
        },
        handleDisChoose () {
            this.isShow = false
        },
        // 根据对象查询属性
        handleChooseObject () {
            if (this.current_selectd_node === '') {
                this.$message.error('请选择对象')
                return false
            }
            this.otherProperyList = []
            this.repPropertyList = []
            this.gisProperyList = []
            this.chacheOtherProperyList = []
            this.form.currentGisPropertye = ''
            let _this = this
            let selectObj = this.current_selectd_node
            let uri = selectObj.uri
            findOperateProperties({ uri: uri }).then(response => {
                let propertyList = response.data
                propertyList = propertyList.filter(ele => {
                    return ele.allowed === '1'
                })
                propertyList.forEach(element => {
                    let type = element.propertyType
                    let representativeuIsone = element.representative
                    if (type === 'GisData') {
                        this.gisProperyList.push(element)
                    }
                    let property = {}
                    property.propertyType = element.propertyType
                    property.propertyUri = element.propertyUri
                    property.displayname = element.displayname
                    if (representativeuIsone === '1') {
                        property.label = true
                        if (type === 'GisData') {
                            property.address = ''
                            property.longitude = ''
                            property.latitude = ''
                        } else if (type === 'TimeInterval') {
                            property.timeStart = ''
                            property.timeEnd = ''
                        } else {
                            property.value = ''
                        }
                        this.repPropertyList.push(Object.assign({}, property))
                    } else {
                        if (type === 'GisData') {
                            property.address = ''
                            property.longitude = ''
                            property.latitude = ''
                        } else if (type === 'TimeInterval') {
                            property.timeStart = ''
                            property.timeEnd = ''
                        } else {
                            property.value = ''
                        }
                        this.otherProperyList.push(Object.assign({}, property))
                        this.chacheOtherProperyList.push(Object.assign({}, property))
                    }
                })
                if (this.gisProperyList.length === 0) {
                    this.$message.error('该对象没有地理属性,请重新选择对象!')
                    return false
                } else {
                    // 如果添加的属性不在属性下拉列表中，则清空当前属性值
                    this.props_arr.forEach((item, index) => {
                        if (_.findIndex(this.chacheOtherProperyList, { propertyUri: item.property.propertyUri }) === -1) {
                            item.property = ''
                            this.props_arr.splice(index, 1, item)
                        }
                    })
                    this.isShow = false
                    this.form.displayname = selectObj.displayname
                    this.form.objectUri = uri
                }
            }).catch(error => {
                _this.$message.error(error.responseJSON.msg)
                return false
            })
        },
        // 表单提交
        handleSubmit () {
            this.$refs.calForm.validate(valid => {
                if (valid) {
                    let params = {
                        objectUri: this.form.objectUri,
                        propertyList: []
                    }
                    // gis属性
                    params.propertyList.push({
                        propertyUri: this.form.currentGisPropertye.propertyUri,
                        propertyType: this.form.currentGisPropertye.propertyType,
                        address: this.form.currentGisPropertye_location,
                        longitude: this.form.currentGisPropertye_longitude,
                        latitude: this.form.currentGisPropertye_latitude
                    })
                    let repPropertyList = this.repPropertyList
                    // 代表属性
                    for (let i = 0; i < repPropertyList.length; i++) {
                        if (repPropertyList[i].propertyType === 'GisData') {
                            if (repPropertyList[i].address === '' || repPropertyList[i].longitude === '' || repPropertyList[i].latitude === '') {
                                this.$message.error('代表属性值不能为空')
                                return false
                            }
                        } else if (repPropertyList[i].propertyType === 'TimeInterval') {
                            if (repPropertyList[i].timeStart === '' || repPropertyList[i].timeEnd === '') {
                                this.$message.error('代表属性值不能为空')
                                return false
                            } else {
                                repPropertyList[i].timeStart = (new Date(repPropertyList[i].timeStart)).getTime()
                                repPropertyList[i].timeEnd = (new Date(repPropertyList[i].timeEnd)).getTime()
                            }
                        } else {
                            if (repPropertyList[i].value === '') {
                                this.$message.error('代表属性值不能为空')
                                return false
                            }
                        }
                        params.propertyList.push(repPropertyList[i])
                    }

                    // 非代表属性
                    for (let i = 0; i < this.props_arr.length; i++) {
                        let property = this.props_arr[i].property
                        if (property && property.propertyUri != this.form.currentGisPropertye.propertyUri) {
                            if (property.propertyType === 'TimeInterval') {
                                if (util.verifyValue(property.propertyType, { startTime: property.timeStart, endTime: property.timeEnd }, property.displayname)) {
                                    property.timeStart = (new Date(property.timeStart)).getTime()
                                    property.timeEnd = (new Date(property.timeEnd)).getTime()
                                } else {
                                    return false
                                }
                            } else if (property.propertyType === 'DateTime') {
                                if (util.verifyValue(property.propertyType, property.value, property.displayname)) {
                                    property.value = (new Date(property.value)).getTime()
                                } else {
                                    return false
                                }
                            } else if (property.propertyType === 'GisData') {
                                if (util.verifyValue(property.propertyType, { address: property.address, longitude: property.longitude, latitude: property.latitude }, property.displayname)) {
                                    params.propertyList.push(property)
                                } else {
                                    return false
                                }
                            } else {
                                if (util.verifyValue(property.propertyType, property.value, property.displayname)) {
                                    params.propertyList.push(property)
                                } else {
                                    return false
                                }
                            }
                        }
                    }
                    saveInstance(params).then(response => {
                        let data = response.data
                        this.closeDialog()
                        let displayName = data.showName ? data.showName : data.displayName
                        this.$emit('spliceObjlist', data.rowkey, data.objectUri, data.objectType, displayName, data.name, data.iconUrl)
                        this.$emit('addMarker', this.position.lng, this.position.lat, data.rowkey, data.objectUri, data.objectType, displayName, data.name, data.iconUrl,data.belongGroup)
                        let newMarker = []
                        let allOverlay = this.map.getOverlays()
                        for(let item of allOverlay){
                        newMarker.push(item.customData)
                        }
                        this.$parent.$parent.$refs.timeLine.getAllDetail(newMarker)
                    })
                }
            })
        },
        // 选择地理属性
        handleChooseGisProperty () {
            this.otherProperyList = this.chacheOtherProperyList.filter(item => item.propertyUri != this.form.currentGisPropertye.propertyUri)
        },
        // 添加非代表属性
        addOtherProperty () {
            this.props_arr.push({ property: '' })
        },
        // 删除非代表属性
        removeOtherProperty (index) {
            this.props_arr.splice(index, 1)
        },
        checkChange (data, node) {
            this.current_selectd_node = data
            this.handleChooseObject()
        },
        // 检查非代表属性是否重复
        checkReadyOnly (property, index) {
            this.otherProperyList = this.chacheOtherProperyList.filter(item => item.propertyUri != this.form.currentGisPropertye.propertyUri)
            let propertyList = this.props_arr.filter((element) => {
                return element.property.propertyUri === property.propertyUri
            })
            if (propertyList.length > 1) {
                this.$message.error('你已经标注表属性，不可重复添加')
                this.props_arr.splice(index, 1, { property: '' })
                return false
            }
        },
        renderContent (h, { node, data }) {
            let img
            if (!util.isEmpty(data.icon)) {
                img = (
                    <img src={data.icon} class="userIcon" width="16px" height="16px" />
                )
            }
            let radio = null
            if (node.level == 1) {
                // 如果是跟节点不让选中
                radio = (
                    <input
                        type="radio"
                        disabled
                        name="object"
                        style="margin-right:12px;margin-top:12px;"
                        on-change={() => this.checkChange(data, node)}
                    />
                )
            } else {
                radio = (
                    <input
                        type="radio"
                        name="object"
                        style="margin-right:12px;margin-top:12px;"
                        on-change={() => this.checkChange(data, node)}
                    />
                )
            }
            return (
                <p>
                    {radio}
                    {img}
                    <span style="margin-left:10px;">{node.label}</span>
                </p>
            )
        }
    }

}
</script>
<style lang="less" >
.mapCalibration {
	.el-checkbox__inner {
	}
	.el-icon-remove {
		color: red;
		font-size: 16px;
	}
	.userIcon {
		position: relative;
		top: 10px;
		border-radius: 16px;
	}
	.el-dialog__header {
		background: #157dd0;
		padding: 10px 20px 10px;
		.el-dialog__title {
			font-size: 16px;
			color: #ffffff;
		}
	}
	.treeDemo {
		width: 60%;
		height: 120px;
		overflow-y: auto;
		position: absolute;
		background-color: #fff;
		z-index: 33;
		border: 1px solid #e0e0e0;
		padding: 10px 0 30px;
		.opreation {
			margin-top: 10px;
			text-align: right;
			padding-right: 10px;
			.el-button {
				padding: 5px 15px;
				line-height: 16px;
			}
		}
	}
}
</style>
